package Main;


import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;


public class BDManagement {

    private Connection conexion;
    private Statement instruccion;
    private ResultSet rs;
    private final String url="jdbc:mysql://localhost:9999/luzanql";
    
//    private final String url="jdbc:mysql://localhost:3306/karentng";
    private final String pass = "luzanql";
    private final String user = "root";
//    private final String pass = "root";
    


    public void conectar() {

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (ClassNotFoundException cnfe) {
            System.out.println("No encontró el controlador");
        } catch (Exception e) {
            System.out.println("Error al crear cargar el controlador");
        }

        conexion = null;
        try {
            conexion = DriverManager.getConnection(url, user, pass);
            System.out.println("Conexion Exitosa!!");
        } catch (Exception e) {
            System.out.println("No se pudo crear la conexión");
            return;
        }

    }

    public int Update(String consulta) {
         int tuplasAfectadas=-1;
        try {
            instruccion = conexion.createStatement();
            tuplasAfectadas =  instruccion.executeUpdate(consulta);
        } catch (SQLException ex) {
            if(ex.getSQLState().equals("23000"))  //23000 error de sql cuando hay tuplas repetidas
                tuplasAfectadas = 0;
            System.out.println("SQLException"+ex.getMessage());
        }
        return tuplasAfectadas;
    }

    public String[][] consultar(String consulta) {
        String[][] tabla = null;
        int filas, columnas;


        try {
            instruccion = conexion.createStatement();
            rs = instruccion.executeQuery(consulta);
            columnas = rs.getMetaData().getColumnCount();
            rs.last();
            filas = rs.getRow();
            rs.first();
            tabla = new String[filas][columnas];
            int j = 0;
            if (filas >= 1) {

                do {
                    for (int i = 0; i < columnas; i++) {
                        tabla[j][i] = rs.getString(i + 1);
                    }
                    j++;
                } while (rs.next());
           }
        } catch (SQLException ex) {
            
        }

        return tabla;
    }
    
    public Statement getSt() {
        conectar();
        try {
            instruccion = conexion.createStatement();
        } catch (SQLException ex) {
            Logger.getLogger(BDManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
        return instruccion;
    }

    public void cerrarConexion() {
        try {
            conexion.close();
        } catch (Exception e) {
            e.toString();
        }
    }

  
}
